<template>
  <div class="user-dropdown">
    <!-- el-dropdown 下拉框核心 -->
    <el-dropdown placement="bottom-end" @command="handleDropdownCommand">
      <div class="avatar-wrapper" >
        <img
            :src="avatarUrl"
            alt="用户头像"
            class="user-avatar"
        />
      </div>

      <!-- 下拉菜单（正确插槽位置） -->
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="avatarUpload">
            <el-icon class="item-icon"><PictureFilled /></el-icon>
            <span>头像上传</span>
          </el-dropdown-item>
          <el-dropdown-item command="editInfo">
            <el-icon class="item-icon"><User /></el-icon>
            <span>修改信息</span>
          </el-dropdown-item>
          <el-dropdown-item command="changePwd">
            <el-icon class="item-icon"><Lock /></el-icon>
            <span>修改密码</span>
          </el-dropdown-item>
          <el-dropdown-item command="logout" type="danger">
            <el-icon class="item-icon"><SwitchButton /></el-icon>
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!--上传头像弹框-->
<el-dialog
        title="上传头像"
        v-model="avatarUploadDialogVisible"
        width="400px"
        :close-on-click-modal="false"
    >
  <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :show-file-list="false"
      :auto-upload="false"
      @change="handleFileChange"
      :before-upload="beforeAvatarUpload"
      accept="image/jpeg,image/png"
  >
    <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  <!-- 弹框底部按钮：取消 + 上传 -->
  <template #footer>
    <el-button @click="avatarUploadDialogVisible = false" class="cancel-btn">取消</el-button>
    <el-button type="primary"
               @click="submitUpload"
               class="confirm-btn"
               :disabled="!selectedFile" >上传头像</el-button>
  </template>
</el-dialog>

    <!-- 修改信息弹窗 -->
    <el-dialog
        title="修改个人信息"
        v-model="infoDialogVisible"
        width="400px"
        :close-on-click-modal="false"
    >  <!--:close-on-click-modal 默认为true   点击对话框外侧会关闭对话框-->
      <el-form
          :model="userInfo"
          label-width="80px"
          :rules="infoFormRules"
          ref="infoFormRef"
      >
        <el-form-item label="管理员">
          <div class="readonly-text">{{ userName }}</div>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userInfo.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="infoDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleUpdateInfo" class="confirm-btn">确认</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
        title="修改密码"
        v-model="pwdDialogVisible"
        width="400px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="passwordForm"
          label-width="80px"
          ref="passwordFormRef"
          :rules="pwdFormRules"
      >
        <el-form-item label="管理员" disabled>
          <div class="readonly-text">{{ userName }}</div>
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pwdDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleUpdatePassword" class="confirm-btn">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElIcon } from 'element-plus';
// 静态导入所有需要的图标
import {User, Lock, SwitchButton, PictureFilled, Plus} from '@element-plus/icons-vue';
import Login from "@/api/login.js";
import AdminApi from "@/api/admin.js"
import { useRouter } from 'vue-router';
import avatar from '@/assets/avatar.jpg'
import {useTokenStore} from "@/stores/tokenStore.js";
// 路由实例
const router = useRouter();
const tokenStore = useTokenStore();
// 表单引用
const infoFormRef = ref(null);
const passwordFormRef = ref(null);

// 弹出框的状态管理
const infoDialogVisible = ref(false);
const pwdDialogVisible = ref(false);
const avatarUploadDialogVisible = ref(false);

// 用户信息
const userInfo = ref({
  nickname: '',
  phone: '',
  email: ''
});

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
//用户名
const userName = ref('');


//头像上传
// 头像地址
const uploadRef=ref(null);
const avatarUrl = ref(); // 初始显示默认头像
// 新增：记录用户选择的文件
const selectedFile = ref(null);
// 1. 选择文件后触发：记录文件到 selectedFile
const handleFileChange = (uploadFile) => {
  selectedFile.value = uploadFile.raw; // uploadFile.raw 是原生 File 对象
  // 可选：生成临时预览图
  avatarUrl.value = URL.createObjectURL(uploadFile.raw);
};



//上传文件校验
const beforeAvatarUpload = (rawFile) => {
  // 校验1：文件格式（仅允许 JPG/PNG）
  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isImage) {
    ElMessage.error('仅支持 JPG、PNG 格式的图片！');
    return false; // 校验失败，阻止后续上传
  }
  // 校验2：文件大小（不超过 2MB）
  const isLt2MB = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2MB) {
    ElMessage.error('头像大小不能超过 2MB，请重新选择！');
    return false; // 校验失败，阻止后续上传
  }

  return true; // 校验通过，允许上传
}


//文件上传
const submitUpload = async () => {
  // 前置校验：确保有选择文件
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要上传的头像！');
    return;
  }
  // 前置校验：调用 beforeAvatarUpload 确认文件合规
  if (!beforeAvatarUpload(selectedFile.value)) {
    return;
  }
  await AdminApi.uploadAvatar(selectedFile.value)
  avatarUploadDialogVisible.value = false;
  selectedFile.value = null; // 重置选择状态，避免重复上传
}



// 信息表单校验规则
const infoFormRules = ref({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
});


// 密码确认校验
const validateConfirmPassword = (rule, value, callback) => {
  if (value!== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 密码表单校验规则
const pwdFormRules = ref({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
});

// 初始化用户名和头像
onMounted(async () => {
  userInfo.value = await AdminApi.getInfo()
  userName.value = await AdminApi.getAdminName();
  const aurl= await AdminApi.getAvatarUrl();
  if (aurl){
    avatarUrl.value=aurl;
  }else{
    avatarUrl.value=avatar;
  }
});


// 下拉菜单命令处理
const handleDropdownCommand = async (command) => {
  switch (command) {
    case 'avatarUpload':
      avatarUploadDialogVisible.value = true;
      break;
    case 'editInfo':
      infoDialogVisible.value = true;
      break;
    case 'changePwd':
      pwdDialogVisible.value = true;
      break;
    case 'logout':
        await Login.adminLogout();
        tokenStore.removeToken();
        await router.push('/login');
      break;
  }
};


// 信息更新处理
const handleUpdateInfo = async () => {
    await infoFormRef.value.validate();
    await AdminApi.editAdminInfo(userInfo.value);
    infoDialogVisible.value = false;
};

// 密码更新处理
const handleUpdatePassword = async () => {
    await passwordFormRef.value.validate();
    // 调用修改密码的API
    await AdminApi.updatePassword(passwordForm);
   await tokenStore.removeToken();
    await router.push('/login');
    pwdDialogVisible.value = false;
    // 重置表单
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
};
</script>

<style scoped>
.user-dropdown {
  display: flex;
  align-items: center;
  z-index: 9999; /* 确保下拉框不被其他元素遮挡 */
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px;
  border-radius: 20px;
  transition: background-color 0.2s;
}

.avatar-wrapper:hover {
  background-color: #f5f5f5; /* hover反馈，提升交互感知 */
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
}


/*用户名显示*/
.readonly-text {
  padding: 0 11px;
  height: 32px;
  line-height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 14px;
  box-sizing: border-box;
  width: 100%;
  user-select: none;
}
/* 下拉菜单样式优化 */
:deep(.el-dropdown-menu) {
  min-width: 160px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

:deep(.el-dropdown-item) {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  transition: background-color 0.2s;
}

:deep(.el-dropdown-item:hover) {
  background-color: #f5f5f5;
}

.item-icon {
  margin-right: 8px;
  font-size: 16px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 弹窗按钮样式 */
:deep(.confirm-btn) {
  background-color: #1677ff !important;
  border-color: #1677ff !important;
  color: white !important;
}

:deep(.cancel-btn) {
  background-color: white !important;
  border-color: #dcdfe6 !important;
  color: #606266 !important;
  margin-right: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}
</style>
